<template>
	<ls-skeleton :loading="loading">
		<scroll-view class="container-scroll" scroll-y="true" :scroll-with-animation="true">
			<view class="container">
				<view class="search-result">
					<view v-if="searchType=='other'" class="address-book-container">
						<!-- 设置为可滚动区域，占据剩余空间 -->
						<scroll-view class="scroll-container uni-list" scroll-y="true" scroll-with-animation="true">
							<swiper indicator-dots="true" autoplay="true" interval="2000" circular
								style="width: 100%; height: 150px;margin-bottom: 10px;">
								<swiper-item v-for="(item, index) in adImages" :key="index">
									<image :src="item.imgUrl" @click="toUrl(item.toUrl)"
										style="width: 100%; height: 100%; object-fit: cover;border-radius: 10rpx;" />
								</swiper-item>
							</swiper>
							<!-- 标题区域（灰色透明框） -->
							<view class="title-box" v-if="keyword">
								<view class="model-detail" @click="searchCarDetail">{{keyword}}</view>
							</view>
							<CarDetail v-if="showDetail" :carInfo="carInfo" :title="modelDetail" :imgUrl="img" />
							<!-- <view class="uni-list" v-for="(p, i) in searchList" :key="i" :id="p.id">
								<view class="uni-list-cell pd-20 title">{{ p.showName }}</view>
								<view class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in p.models"
									:key="index"
									@click="getModelDetail(item.modelId, 'yearRight',p.brandName + item.modelName)">
									<view class="uni-list-cell-db">
										<view class="contact-name">{{ item.modelName }}</view>
									</view>
								</view>
							</view> -->
						</scroll-view>
						<!-- goUrl('/pages/home/detail/index?modelId=' + item.modelId + '&title=' + p.brandName + item.modelName) -->
					</view>
				</view>
				<uni-drawer ref="yearRight" :width="200" :height="'50%'" mode="right">
					<view class="scroll-view">
						<scroll-view class="scroll-view-box" scroll-y="true">
							<view class="info-content" @click="onSaleNameChange(cc)" v-for="cc in saleCC" :key="cc">
								<text>{{cc}}</text>
							</view>
						</scroll-view>
					</view>
				</uni-drawer>
				<uni-drawer ref="showRight" :width="200" :height="'50%'" mode="right">
					<view class="scroll-view">
						<scroll-view class="scroll-view-box" scroll-y="true">
							<view class="info-content" @click="goCarDetail(item)" v-for="item in saleNames" :key="item">
								<text>{{item}}</text>
							</view>
						</scroll-view>
					</view>
				</uni-drawer>
				<!-- <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button> -->

				<!-- 				<view v-if="searchType=='vin'" class="address-book-container">
					<scroll-view class="scroll-container uni-list" scroll-y="true" scroll-with-animation="true">
						<view class="title-box" v-if="modelDetail">
							<view class="model-detail">{{modelDetail}}</view>
						</view>
						<view class="item" v-if="factory">
							<text class="label">厂家</text>
							<text class="value">{{factory}}</text>
						</view>
						<view class="item" v-if="salesVersion">
							<text class="label">销售版本</text>
							<text class="value">{{salesVersion}}</text>
						</view>
						<view class="item" v-if="cc">
							<text class="label">动力</text>
							<text class="value">{{cc}}</text>
						</view>
						<view class="item" v-if="modelYear">
							<text class="label">年份</text>
							<text class="value">{{modelYear}}</text>
						</view>
						<view class="item" v-if="model">
							<text class="label">系列</text>
							<text class="value clickable" @click="goToDetail">{{model}}</text>
						</view>

						<view class="item" v-if="carInfo.remark">
							<text class="label">备注</text>
							<text class="value">{{carInfo.remark}}</text>
						</view>
						<view class="item" v-if="carInfo.jinDeng">
							<text class="label">近光</text>
							<text class="value clickable"
								@click="fetchProductList(carInfo.jinDeng)">{{carInfo.jinDeng}}</text>
						</view>
						<view class="item" v-if="carInfo.yuanDeng">
							<text class="label">远光</text>
							<text class="value clickable"
								@click="fetchProductList(carInfo.yuanDeng)">{{carInfo.yuanDeng}}</text>
						</view>
						<view class="item" v-if="carInfo.wuDeng">
							<text class="label">雾灯</text>
							<text class="value clickable"
								@click="fetchProductList(carInfo.wuDeng)">{{carInfo.wuDeng}}</text>
						</view>
						<view class="item" v-if="carInfo.gsJinDengName">
							<text class="label">格栅近光灯</text>
							<text class="value clickable"
								@click="fetchProductList(carInfo.gsJinDengName)">{{carInfo.gsJinDengName}}</text>
						</view>
						<view class="item" v-if="carInfo.gsYuanDengName">
							<text class="label">格栅远光灯</text>
							<text class="value">{{carInfo.gsYuanDengName}}</text>
						</view>
						<view class="item" v-if="carInfo.exchangeDengVideoUrl">
							<text class="label">换灯视频</text>
							<text class="value">{{carInfo.exchangeDengVideoUrl}}</text>
						</view>
						<view class="item" v-if="carInfo.kapan">
							<text class="label">专用卡座</text>
							<text class="value">{{carInfo.kapan}}</text>
						</view>
						<view class="item" v-if="carInfo.jieMa">
							<text class="label">解码器</text>
							<text class="value">{{carInfo.jieMa}}</text>
						</view>
						<view class="item" v-if="carInfo.fangchenzhao">
							<text class="label">防尘罩</text>
							<text class="value">{{carInfo.fangchenzhao}}</text>
						</view>
						<view class="item" v-if="carInfo.installEasy">
							<text class="label">安装难易</text>
							<text class="value">{{carInfo.installEasy}}</text>
						</view>
						<view class="item" v-if="carInfo.changeDengVideoUrl">
							<text class="label">改装视频</text>
							<text class="value">{{carInfo.changeDengVideoUrl}}</text>
						</view>
						<view class="item" v-if="carInfo.originGlueType">
							<text class="label">原胶类型</text>
							<text class="value">{{carInfo.originGlueType}}</text>
						</view>
						<view class="item" v-if="carInfo.standSupport">
							<text class="label">专用支架</text>
							<text class="value">{{carInfo.standSupport}}</text>
						</view>
						<view class="item" v-if="carInfo.jieMa">
							<text class="label">是否解码</text>
							<text class="value">{{carInfo.jieMa}}</text>
						</view>
						<view class="item" v-if="carInfo.allJoinRemark">
							<text class="label">大灯总成</text>
							<text class="value">{{carInfo.allJoinRemark}}</text>
						</view>
					</scroll-view>
				</view> -->

				<!-- <view class="search uni-inline-item" style='display: none;'>
					<icon type="search" size="14" />
					<view class="uni-flex-item">
						<input type="text" class="uni-input" v-model="keyword" placeholder="输入关键字进行搜索"
							@click="goUrl('/pages/home/search/index')" />
					</view>
				</view> -->
				<!-- 	<view class="scroll">
					<scroll-view class="scroll-view_H" scroll-x="true" scroll-with-animation :scroll-left="tabLeft">
						<block v-for="(item, index) in tablist" :key="index">
							<view :class="['scroll-view-item_H', tabClick == index ? 'on' : '']"
								@click="longClick(index, item.selectName)"> {{ item.selectName }} </view>
						</block>
					</scroll-view>
				</view>
				<view class="title">热门车型</view>
				<view class="lists">
					<view class="bd" v-for="(item, index) in list" :key="index"
						@click="goUrl('/pages/home/detail/index?modelId=' + item.modelId + '&title=' + item.modelFullName)">
						<view class="box">
							<image mode="widthFix" :src="item.modelImageUrl || '../../static/images/carDefault.png'"
								class="pic"></image>
							<view class="p line1">{{item.modelFullName}}</view>
						</view>
					</view>
				</view> -->
			</view>
		</scroll-view>
		<view class="container-bottom">
			<!-- 输入框部分 -->
			<!-- <view class="input-container"> -->
			<!-- <view class="badge" v-if="vinCodeCount > 0"> -->
			<!-- 已识别车架号：{{ vinCodeCount }} -->
			<!-- </view> -->
			<!-- <view class="input-box">
				<input type="text" class="input-field" placeholder="请输入17位车架号" v-model="vinCode" /> -->
			<!-- 搜索图标 -->
			<!-- <button @click="searchVin()" class="search-btn">搜索</button>
			</view> -->

			<!-- </view> -->
			<!-- 用 flexbox 分成两部分，左侧为语音识别，右侧为相机扫描 -->
			<view class="flex-row" style="position: relative;">
				<!-- 左侧相机扫描车架号功能 -->
				<view class="camera-container flex-item" style="position: relative;">
					<!-- 左侧相册功能 -->
					<view @click="goToVin()" class="mic-container flex-item"
						style="position: absolute;left: 0;bottom: 0;">
						<!-- 搜索图标 -->
						<view>
							<image style="width: 35px;height: 15px;" src="@/static/images/shurukuang.png"></image>
						</view>
						<!-- 标题 -->
						<view class="title" style="text-align: center; margin-top: 10px; margin-bottom: 20rpx;">
							输入VIN码
						</view>
					</view>

					<!-- 相机识别图标 -->
					<view style="position: absolute; bottom: 40px; left: 50%; transform: translateX(-50%);">
						<button type="primary" @click="openCamera" class="camera-button">
						</button>
					</view>
					<view style="text-align: center;font-size: 16px;font-weight: bold;margin-top: 30px;">
						请拍车架号
					</view>


					<!-- 右侧搜索功能 -->
					<view class="mic-container flex-item" style="position: absolute;right: 0;bottom: 0;">
						<!-- 搜索图标 -->
						<view @click="goUrl('/pages/home/search/index')">
							<u-icon name="search" size="80" color="#00a128"></u-icon>
						</view>
						<!-- 标题 -->
						<view class="title" style="text-align: center; margin-top: 10px; margin-bottom: 50rpx;">
							语音查询
						</view>
					</view>
				</view>



				<camera v-if="cameraOn" device-position="back" flash="off" binderror="cameraError"
					style="width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; z-index: 1000;"></camera>
				<view v-if="cameraOn && showButtons"
					style="position: absolute;  bottom: 40px; left: 50%; transform: translateX(-50%); z-index: 1001;">
					<button type="primary" @click="startCamera" class="camera-button">
					</button>
				</view>
				<view v-if="cameraOn && showButtons" @click="cameraOn = false;showButtons = false"
					style="position: absolute; bottom: 40px; right: 20px; z-index: 1001;">
					<image style="width: 50px;height: 65px;" src="@/static/images/quxiao.png"></image>
					<!-- <button @click="cameraOn = false;showButtons = false">取消</button> -->
				</view>
				<!-- <view v-if="cameraOn && showButtons" @click="photoAlbum" class="camera-icon" -->
				<!-- style="position: absolute; top: 20px; left: 20px; z-index: 1001;"> -->
				<!-- <button @click="photoAlbum">相册</button> -->
				<!-- <image style="width: 35px;height: 40px;" src="@/static/images/xiangce.png"></image> -->
				<!-- </view> -->
				<!-- <button @click="openCamera">打开相机拍照</button> -->

				<!-- 中部语音识别功能 -->
				<!-- <view class="mic-container flex-item"> -->
				<!-- 语音识别图标 -->
				<!-- 					<view :class="['row-center', 'fixed-mic', {active: isRecording}]" @touchstart="streamRecord"
						@touchend="endStreamRecord">
						<u-icon name="mic" size="80" :color="micColor"></u-icon>
					</view> -->
				<!-- 标题 -->
				<!-- 					<view class="title" style="text-align: center;margin-top: 10px;margin-bottom: 50rpx;">
						说车型
					</view> -->
				<!-- </view> -->


			</view>
		</view>
	</ls-skeleton>
</template>


<script>
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		USER_INFO
	} from '../../config/cache';
	import test from '../../uni_modules/uview-ui/libs/function/test';
	import {
		getList,
	} from '@/api/product.js';
	import {
		getCarTypeSel,
		getCarModel,
		getMd5Token,
		vinCode,
		getCountVin,
		searchCarDetail,
		getBrandModel,
		getSaleNameByModelId,
		getCCByModelId
	} from '@/api/car.js';
	import {
		getAdvertisement,
		saveVinLog,
	} from '@/api/common.js';
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import CarDetail from '@/pages/commponent/car_detail_moudel.vue'; // 引入组件
	import {
		mapGetters
	} from "vuex";
	// 获取设备宽度
	let isWidth = uni.getSystemInfoSync().windowWidth;
	let plugin = requirePlugin("WechatSI");
	let manager = plugin.getRecordRecognitionManager();
	export default {
		components: {
			CarDetail,
		},
		data() {
			return {
				showDetail: false,
				title: '',
				saleCC: [],
				saleNames: [],
				selectSaleName: '',
				selectCC: '',
				showButtons: false,
				cameraOn: false, // 控制相机组件的显示与隐藏
				tabs: [{
						text: '动态',
						icon: '../../static/images/user_06.png',
						url: '/pages/dynamic/index',
					},
					{
						text: '直播间',
						icon: '../../static/images/user_14.png',
						url: '/pages/live/index',
					},
					{
						text: '活动',
						icon: '../../static/images/user_07.png',
						url: '/pages/activity/index',
					},
					{
						text: '客服',
						icon: '../../static/images/user_16.png',
						url: 'contact',
					},
				],
				vinCodeCount: 0, //用户提供的有效车架号
				vinCode: '', //车架号
				adImages: [],
				tabClick: 0,
				tablist: [],
				// isWidth: 0, //每个导航栏占位
				isWidth: (isWidth - 65) / 4, //每个导航栏占位
				tabLeft: 0,
				selectName: '',
				list: [],
				searchList: [],
				loading: true,
				isRecording: false, // 录音状态
				isListening: false, //监听状态
				token: '',
				imagePath: '', // 图片路径
				startX: 0,
				startY: 0,
				width: 0,
				height: 0,
				isDrawing: false,
				toView: '',
				indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
					'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				],
				keyword: '',
				vin: '',
				modelDetail: '',
				brand: '',
				series: '',
				modelYear: '',
				model: '',
				modelId: '',
				salesVersion: '',
				cc: '',
				factory: '',
				searchType: 'other',
				carInfo: [],
				img: '',
			}

		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				userType: 'userType',
				bgUserType: 'bgUserType'
			}),
			// 动态设置图标的颜色
			micColor() {
				return this.isRecording ? '#b40407' : '#00a128';
			}
		},
		onLoad(options) {
			let that = this;
			//拍照传过来的参数
			that.vinCode = options.vin || '';
			if (options.vinCode) {
				that.vinCode = options.vinCode;
				this.searchVin()
			}
			that.carInfo = uni.getStorageSync('carInfo')
			that.showDetail = options.showDetail || false;
			that.keyword = options.keyword || '';
			uni.removeStorageSync('carInfo')
			// if (that.isLogin == false) {
			// 	toLogin();
			// }
			/**
			 * 首页数据
			 */
			that.getCarTypeSel();


		},

		onShow() {
			this.initRecord();
			this.getAdvertisement();
			if (this.isLogin) {
				this.getCountVin();
			}
		},

		methods: {
			/**
			 * 分享
			 */
			shareCard() {
				uni.showShareMenu({
					//小程序的原生菜单中显示分享按钮，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
					menus: ["shareAppMessage", "shareTimeline"] //不设置默认发送给朋友
				})
			},
			// 分享到朋友
			onShareAppMessage(res) {
				console.log("aaa");
				let that = this;
				//这块需要传参，不然链接地址进去获取不到数据
				return {
					title: that.title,
					path: 'pages/index/index?vinCode=' + that.vinCode,
					imageUrl: ''
				};
			},
			
			//分享到朋友圈
			onShareTimeline(res) {
				let that = this;
				//这块需要传参，不然链接地址进去获取不到数据
				return {
					title: that.title,
					path: 'pages/index/index?vinCode=' + that.vinCode,
					imageUrl: ''
				};
			},
			goToVin() {
				this.$util.Tips("/pages/commponent/car_vin");
			},
			toUrl(url) {
				this.$util.Tips(url);
			},
			goCarDetail(saleName) {
				console.log(saleName);
				this.selectSaleName = saleName;
				this.$util.Tips('/pages/home/detail/index?modelId=' + this.modelId + '&saleName=' + this.selectSaleName +
					'&cc=' + this.selectCC + '&title=' + this.title)
			},
			onSaleNameChange(cc) {
				this.selectCC = cc;
				getSaleNameByModelId({
					modelId: this.modelId,
					cc: cc
				}).then(res => {
					this.saleNames = res.value;
					if (this.saleNames.length === 0) {
						this.selectSaleName = '';
						this.$util.Tips('/pages/home/detail/index?modelId=' + this.modelId + '&saleName=' + this
							.selectSaleName + '&cc=' + this.selectCC + '&title=' + this.title)
					} else {
						this.$refs["showRight"].open();
					}
				})
			},
			getModelDetail(modelId, e, title) {
				this.saleNames = [];
				this.saleCC = [];
				let that = this;
				this.modelId = modelId;
				this.title = title;
				getCCByModelId({
					modelId: modelId
				}).then(res => {
					this.saleCC = res.value;
					this.$refs[e].open()
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},
			handleTabClick(e) {
				const {
					text
				} = e.currentTarget.dataset;

				if (text === '客服') {
					// 直接打开客服
					wx.openCustomerServiceChat({
						sessionFrom: 'sessionFrom',
						success() {
							console.log('客服打开成功');
						},
						fail(err) {
							console.error('客服打开失败', err);
						},
					});
				} else {
					// 显示功能暂未开放
					wx.showToast({
						title: '此功能暂未开放',
						icon: 'none',
						duration: 2000, // 提示显示时长
					});
				}
			},
			goToDetail() {
				if (this.carInfo != null) {
					uni.navigateTo({
						url: `/pages/home/detail/index?modelId=${this.carInfo.modelId}&title=${this.carInfo.carName}`
					});
				}
			},
			// 上传图片文件
			uploadImage(filePath) {
				// 显示加载提示
				uni.showLoading({
					title: '处理中...',
					mask: true, // 遮罩层，防止用户点击其他区域
				});
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/car/getMd5Token',
					//url: 'http://localhost:8930/car/getMd5Token',
					filePath: filePath,
					name: 'file', // 参数名，后端获取的字段
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes.data);
						// 如果后端返回的字符串是 JSON 格式，尝试解析
						try {
							const parsedData = JSON.parse(uploadRes.data);
							console.log(parsedData)
							this.callVinApi(parsedData); // 将解析后的数据传递给下一个函数
						} catch (error) {
							console.error("JSON 解析失败:", error);
						}
					},
					fail: (err) => {
						console.error('未识别到有效信息:', err);
						uni.showToast({
							title: '未识别到有效信息，请重试',
							icon: 'none',
						});
					},
					complete: () => {
						console.log(this.modelDetail);
						// 无论请求成功或失败，都隐藏加载提示
						uni.hideLoading();
					}
				});
			},

			searchVin() { //输入框查询车架号
				if (!this.vinCode || this.vinCode.length !== 17) {
					uni.showToast({
						title: '请输入17位有效车架号',
						icon: 'none',
					});
					return;
				}
				vinCode({
					vinCode: this.vinCode
				}).then(res => {
					this.callVinApi(res);
				}).catch(err => {
					console.error("请求失败，错误信息：", err); // 打印错误信息
					this.$util.Tips({
						title: "根据车架号查询错误"
					});
				});
			},
			// 根据返回内容查询
			callVinApi(uploadResponse) {
				// 判断 uploadResponse 和 uploadResponse.value 是否为 null 或 undefined
				if (!uploadResponse || !uploadResponse.value) {
					uni.showToast({
						title: '数据为空',
						icon: 'none',
					});
					return; // 如果上传响应数据不合法，直接返回，不继续执行后面的逻辑
				}
				const {
					brand,
					series,
					modelDetail,
					Model,
					vin,
					modelYear,
					salesVersion,
					cc,
					factory,
					img,
				} = uploadResponse.value;
				// 连接品牌和系列
				const brandModel = `${factory}${Model}`;

				this.modelDetail = `${modelDetail}`;
				this.vin = `${vin}`;
				this.brand = `${brand}`
				this.series = `${series}`
				this.model = `${Model}`
				this.modelYear = `${modelYear}`
				this.salesVersion = `${salesVersion}`
				this.cc = `${cc}`
				this.factory = `${factory}`
				this.img = `${img}`

				this.keyword = this.modelDetail;
				console.log("搜索条件：" + brandModel)
				this.getSearchKeyAndBrand(brandModel, brand)
					.then(() => {
						if (this.searchList.length > 0) { // 确保 searchList 被正确赋值后判断
							this.saveVinLog("正常查询");
						}
					})
					.catch(error => {
						console.error("获取搜索数据失败:", error);
						this.saveVinLog("未查询到内容");
					});
				// this.searchType = 'vin'; //搜索方式设定
				this.vinCode = this.vin
			},
			searchCarDetail() {
				this.showDetail = false;
				// 查具体信息 wxCar 表内容
				searchCarDetail({
					factory: this.factory,
					model: this.model,
					modelYear: this.modelYear,
					salesVersion: this.salesVersion,
					cc: this.cc,
					brand: this.brand,
					userId: this.uid
				}).then(res => {
					console.log(this.model);
					if (res.value != null) {
						this.carInfo = res.value;
						console.log("有具体车型：" + res.value.carId);
						const jinDeng = this.carInfo.jinDeng;
						const yuanDeng = this.carInfo.yuanDeng;
						const wuDeng = this.carInfo.wuDeng;
						// 判断字段是否为空、null 或 undefined
						this.showDetail = true;
						// if (jinDeng && jinDeng.trim() !== '' || yuanDeng && yuanDeng.trim() !== '' || wuDeng &&
						// 	wuDeng.trim() !== '') {
						// 	// uni.setStorageSync('carInfo', this.carInfo);
						// 	// // 跳转到目标页面
						// 	// uni.navigateTo({
						// 	// 	url: `/pages/home/detail/car_detail?id=${this.carInfo.carId}&title=${this.modelDetail}&imgUrl=${this.img}`,
						// 	// });

						// }
					} else {
						this.carInfo = [];
						// 提示暂无信息
						console.log("无具体车型：" + this.modelDetail);
					}
				}).catch(error => {
					console.error("查询具体车型失败：", error);
					// 可选：捕获错误并提示
					uni.showToast({
						title: '查询失败，请稍后重试',
						icon: 'none',
						duration: 2000
					});
				});
			},
			saveVinLog(message) {
				// 存入vin码日志
				saveVinLog({
					userId: this.uid || '', // 确保 userId 不为空
					vin: this.vin,
					type: message,
					brand: this.brand,
					series: this.series,
					model: this.model,
					modelYear: this.modelYear,
					modelDetail: this.modelDetail,
					salesVersion: this.salesVersion,
					cc: this.cc,
					factory: this.factory,
					img: this.img,
				}).then(res => {
					this.img = res.value.img;
					console.log("保存后返回的图片" + res.value.img)
					this.searchCarDetail();
				});
				this.getCountVin(); // 计数（该用户有效vin码记录）
			},
			getCountVin() { //获取该用户上传有效车架号信息
				getCountVin({
						userId: this.uid ? this.uid : '',
					}).then(res => {
						// 处理成功的响应
						if (res && res.value) {
							this.vinCodeCount = res.value.length
						} else {
							console.log('无数据');
						}
					})
					.catch(error => {
						uni.showToast({
							title: '获取有效车架号错误',
							icon: 'none',
						});
					});
			},
			/**
			 * 获取搜索
			 */
			getSearch(keyword) {
				this.searchType = "other";
				return new Promise((resolve, reject) => {
					this.searchList = [];
					this.$request.get("car/getKey", {
						keyWord: keyword,
						keyWord: keyword,
					}).then(res => {
						this.searchList = res.value;
						resolve(res); // 确保在获取数据后执行后续逻辑
					}).catch(err => {
						this.$util.Tips({
							title: err
						});
						reject(err); // 请求失败时拒绝
					});
				});
			},
			/**
			 * 获取搜索
			 */
			getSearchKeyAndBrand(keyword, brand) {
				this.searchType = "other";
				return new Promise((resolve, reject) => {
					this.searchList = [];
					this.$request.get("car/getKeyAndBrand", {
						keyWord: keyword,
						brand: brand,
					}).then(res => {
						this.searchList = res.value;
						resolve(res); // 确保在获取数据后执行后续逻辑
					}).catch(err => {
						this.$util.Tips({
							title: err
						});
						reject(err); // 请求失败时拒绝
					});
				});
			},
			getAdvertisement() {
				getAdvertisement({})
					.then(res => {
						// 处理成功的响应
						if (res && res.value) {
							this.adImages = res.value; // 将返回的广告数据赋值给 adImages
						} else {
							console.error('未获取到广告数据');
						}
					})
					.catch(error => {
						// 错误处理
						console.error('获取广告数据失败:', error);
					});
			},
			openCamera() {
				// if (this.isLogin == false) {
				// 	toLogin();
				// 	return;
				// }
				this.$util.Tips("/pages/commponent/take_picture");
				// this.cameraOn = true;
				// this.$nextTick(() => {
				// 	// 使用 setTimeout 确保 camera 组件完全加载完成
				// 	setTimeout(() => {
				// 		this.showButtons = true; // 假设你有一个 showButtons 数据属性来控制按钮的显示
				// 	}, 300); // 300ms 延迟，可以根据实际情况调整
				// });
			},
			/**
			 * 相机插件
			 */
			startCamera() {
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				// 创建相机上下文
				const ctx = uni.createCameraContext();
				// 拍照
				ctx.takePhoto({
					quality: 'high', // 拍照质量
					success: (res) => {
						// 获取图片路径
						const filePath = res.tempImagePath;
						console.log('拍摄成功，图片路径:', filePath);
						// 压缩图片
						uni.compressImage({
							src: filePath,
							quality: 80, // 质量 80%
							success: (compressRes) => {
								const compressedPath = compressRes.tempFilePath;
								// 上传图片文件
								this.uploadImage(compressedPath); // 上传压缩后的图片文件
								this.cameraOn = false;
								this.showButtons = false;
							},
							fail: (err) => {
								uni.showToast({
									title: '图片压缩失败',
									icon: 'none',
								});
							}
						});
					},
					fail: (err) => {
						console.error('拍摄失败:', err);
						uni.showToast({
							title: '拍摄失败',
							icon: 'none',
						});
					}
				});
			},
			photoAlbum() {
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				// 打开相机拍照
				uni.chooseImage({
					count: 1, // 只能选择一张图片
					sourceType: ['album'], // 允许使用相机和相册
					success: (res) => {
						// 获取图片路径
						const filePath = res.tempFilePaths[0];
						console.log('识别成功，图片路径:', filePath);
						// 压缩图片
						uni.compressImage({
							src: filePath,
							quality: 80, // 质量 80%
							success: (compressRes) => {
								const compressedPath = compressRes.tempFilePath;
								// 上传图片文件
								this.uploadImage(compressedPath); // 上传压缩后的图片文件
								this.cameraOn = false;
								this.showButtons = false;
							},
							fail: (err) => {
								uni.showToast({
									title: '图片压缩失败',
									icon: 'none',
								});
							}
						});
					},
					fail: (err) => {
						console.error('识别取消:', err);
						uni.showToast({
							title: '识别取消',
							icon: 'none',
						});
					}
				});

			},
			longClick(index, selectName) {
				let that = this;
				that.tabClick = index;
				that.selectName = selectName;
				if (that.tablist.length > 3) {
					that.tabLeft = (index - 3) * that.isWidth;
					console.log(that.tabLeft);
				}
				that.getCarModel(that.selectName);
			},
			/**
			 * 语音插件
			 */
			streamRecord() {
				let that = this;
				this.isRecording = true; // 按下时显示录音状态
				this.isListening = true; // 开始监听
				console.log('=======开始====' + this.isRecording + this.isListening)
				uni.getSetting({
					success(res) {
						console.log(res);
						if (res && res.authSetting && res.authSetting.hasOwnProperty('scope.record')) {
							if (res.authSetting['scope.record']) {
								manager.start({
									lang: 'zh_CN',
								});
							} else {
								uni.showModal({
									content: '检测到您还没打开麦克风，是否去设置打开？',
									confirmText: "确认",
									cancelText: "取消",
									success: function(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													console.log(res);
													manager.start({
														lang: 'zh_CN',
													})
												}
											});
										}
									}
								})
							}
						} else {
							manager.start({
								lang: 'zh_CN',
							})
						}
					}
				});

			},
			endStreamRecord() {
				this.isRecording = false; // 松开时隐藏录音状态
				this.isListening = false; // 结束监听
				manager.stop()
				console.log('=======结束====' + this.isRecording + this.isListening)

				// this.resetRecognition(); // 重置识别状态
			},
			/**
			 * 
			 */
			initRecord() {
				//有新的识别内容返回，则会调用此事件
				manager.onRecognize = (res) => {
					this.isRecording = true; // 按下时显示录音状态
					let text = res.result
					console.log("有新的识别内容返回，则会调用此事件")
					this.keyword = text.replace("。", "")
				}
				// 识别结束事件
				manager.onStop = (res) => {
					this.isRecording = false; // 松开时隐藏录音状态
					this.isListening = false; // 结束监听
					let text = res.result
					console.log(text)
					if (text == '') {
						console.log('没有说话')
						manager.stop()
						return
					}
					this.keyword = text.replace("。", "")

					this.modelDetail = this.keyword
					// 跳转到搜索页面并传递 keyword 参数
					// uni.navigateTo({
					// 	url: `/pages/home/search/index?keyword=${this.keyword}`
					// });
					this.getSearch(this.keyword);
				}
			},
			// 重置识别状态
			// resetRecognition() {
			// 	setTimeout(() => {
			// 		if (!this.isListening) {
			// 			console.log('重新初始化语音识别');
			// 			manager.stop();
			// 			manager.start({
			// 				lang: 'zh_CN'
			// 			}); // 重新启动识别
			// 		}
			// 	}, 1000); // 延迟500ms，确保状态清理完成后再重新启动
			// },
			/**
			 * 获取热门车型列表
			 */
			getCarTypeSel() {
				let that = this;
				that.loading = false;
				// getCarTypeSel().then(res => {
				// 	that.tablist = res.value;
				// 	that.selectName = res.value[that.tabClick].selectName;
				// 	// that.getCarModel(that.selectName);

				// }).catch(err => {
				// 	that.$util.Tips({
				// 		title: err
				// 	});
				// })
			},
			/**
			 * @param {Object} carType
			 * 获取热门车型列表
			 */
			getCarModel(carType) {
				let that = this;
				getCarModel({
					carType: carType
				}).then(res => {
					that.list = res.value;
					console.log(res);
				}).catch(err => {
					that.$util.Tips({
						title: res.message
					});
				})
			},

			goUrl(url) {
				this.$util.Tips(url);
			},

			//关于搜索结果条
			toSelectIndex(item, Inv) {
				this.toView = item
				this.navIdx = Inv;
			},
			fetchProductList(itemName) {
				if (itemName != 'LED') {
					getList({
							itemName: itemName,
						})
						.then(res => {
							if (res && res.value && res.value.list) {
								if (res.value.list.length === 1) {
									const categoryId = res.value.list[0].categoryId; // 获取唯一对象的 categoryId
									const url = `/pages/goods/goods_detail/index?productId=${categoryId}&type=STORE`;
									uni.navigateTo({
										url: url,
									});
								} else if (res.value.list.length > 1) {
									const url =
										`/pages/goods/goods_list/index?typeId=${ res.value.list[0].itemTypeId }&itemName=${itemName}&type=${this.userType}`;
									uni.navigateTo({
										url: url,
									});
								} else {
									// 如果没有数据，显示弹窗提示
									uni.showToast({
										title: '暂无数据',
										icon: 'none', // 只显示文字，没有图标
										duration: 2000 // 弹窗持续2秒
									});
								}
							}
						})
						.catch(err => {
							// this.$util.Tips({
							// 	title: err.message || "获取产品列表失败"
							// });
						})
				}
			},
		}
	}
</script>

<style>
	.scroll-view-box {
		flex: 1;
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
	}

	.info-content {
		padding: 10px 15px;
		border-bottom: 1px solid #eaeaea;
		/* 添加下划线 */
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #ffffff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果 */
		transition: all 0.3s ease;
		/* 添加过渡效果 */
		cursor: pointer;
	}

	.camera-icon {
		width: 100rpx;
		/* 按钮直径 */
		height: 100rpx;
		/* 按钮直径 */
		background-color: rgba(200, 200, 200, 0.5);
		/* 灰色透明背景 */
		border-radius: 50%;
		/* 添加白色半透明边框 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		/* 添加阴影效果 */
		display: flex;
		/* 使用 flex 布局 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	.camera-button {
		width: 160rpx;
		/* 按钮直径 */
		height: 160rpx;
		/* 按钮直径 */
		background-color: #00a128;
		/* 按钮颜色 */
		border-radius: 50%;
		/* 使按钮呈圆形 */
		border: 2px solid #ffffff;
		/* 添加白色边框，类似微信的样式 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		/* 添加阴影效果 */
	}

	//角标
	.badge {
		font-size: 12px;
		/* 调整字体大小 */
		color: #999;
		/* 设置灰色字体 */
		text-align: center;
		/* 居中显示 */
		margin-bottom: 10px;
		/* 给文字和下方输入框之间留一些空间 */
	}

	/* 标题区域 */
	.title-box {
		background-color: rgba(169, 169, 169, 0.3);
		/* 淡灰色透明背景 */
		padding: 10px;
		text-align: center;
		/* 与下方滚动区域之间的间距 */
		border-radius: 25rpx;
		width: 600rpx;
		margin: 0 auto;
		/* 水平居中 */
	}

	.model-detail {
		font-size: 35rpx;
		font-weight: bold;
		color: #333;
	}

	.container-scroll {
		/* 占据整个屏幕高度 */
		overflow-y: auto;
	}

	/* 容器样式 */
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* 图片居中 */
	}

	/* 图片样式 */
	.avatar-image {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		margin-top: 20px;
		/* 上间距 */
		margin-bottom: 30rpx;
		/* 下间距 */
	}

	/* 搜索结果区域样式 */
	.search-result {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	/* 地址容器，使用 flex 布局 */
	.address-book-container {
		margin-top: 40rpx;
		height: 100%;
		width: 100%;
		/* 设置剩余高度，减去其他元素的高度 */
		overflow: hidden;
	}

	/* 左侧通讯录部分 */
	.scroll-container {
		flex: 1;
		/* 占据剩余空间 */
		overflow-y: auto;
		height: 100%;
		/* 高度占满父容器 */
		width: 600rpx;
		margin: 0 auto;
		/* 水平居中 */
	}



	/* 	.container {
		padding: 0 40rpx;
		height: 300px;
	} */

	.container .search {
		background: #F6F7F9;
		border-radius: 60rpx;
		padding: 0 30rpx;
		margin-bottom: 10rpx;
	}

	.container .search input {
		background: none;
	}

	.container .scroll-view_H {
		white-space: nowrap;
	}

	.container .scroll-view-item_H {
		display: inline-block;
		vertical-align: middle;
		margin-right: 40rpx;
		padding: 15rpx 0;
		position: relative;
	}

	.container .scroll-view-item_H.on {
		font-weight: bold;
		font-size: 36rpx;
		color: #06A972;
	}

	.container .scroll-view-item_H.on::after {
		content: '';
		display: block;
		height: 4rpx;
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		background: #06A972;
		border-radius: 2px 2px 2px 2px;
	}

	.container .title {
		font-size: 32rpx;
		font-weight: bold;
		color: #06A972;
		background-color: #f5f5f5;
		margin-top: 10rpx;
		padding-bottom: 10rpx;
	}

	.uni-list-cell-db {
		font-size: 29rpx;
	}

	.container .lists {
		display: flex;
		flex-wrap: wrap;
		margin: -15rpx;
	}

	.container .lists>view {
		width: 33.333%;
		box-sizing: border-box;
		padding: 15rpx;
		text-align: center;
	}

	.container .lists .box {
		border-radius: 14rpx;
		border: 1px solid #E8E8E8;
		padding: 20rpx 0 25rpx;
	}

	.container .lists .box image {
		width: 140rpx;
		height: 140rpx;
		margin: 0 auto 25rpx;
	}

	.container .lists .box .p {
		padding: 0 6rpx;
	}

	//底部功能
	.container-bottom {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		background: white;
	}

	.title {
		padding: 0rpx;
		font-size: 24rpx;
		text-align: center;
		margin-top: 50px;
	}

	.flex-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		margin-top: 20rpx;
	}

	.flex-item {
		width: 33%;
		/* 分配一半的空间 */
		display: flex;
		flex-direction: column;
		/* 让标题和内容垂直排列 */
		justify-content: center;
		align-items: center;
	}

	.mic-container,
	.camera-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.mic-container {
		/* 麦克风图标位置调整 */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.mic-icon {
		position: relative;
		z-index: 2;
	}

	/* 激活时的光圈效果 */
	.fixed-mic.active::after,
	.fixed-mic.active::before {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		width: 120px;
		height: 120px;
		margin-top: -60px;
		margin-left: -60px;
		border-radius: 50%;
		background-color: rgba(0, 152, 0, 0.2);
		opacity: 0;
		transform: scale(0);
		animation: pulse 1.5s ease-out infinite;
		pointer-events: none;
	}

	.fixed-mic.active::before {
		animation: pulse2 1.5s ease-out infinite;
	}

	/* 光圈动画 */
	@keyframes pulse {
		0% {
			opacity: 0.2;
			transform: scale(0);
		}

		50% {
			opacity: 0.7;
			transform: scale(1.5);
		}

		100% {
			opacity: 0;
			transform: scale(2.5);
		}
	}

	@keyframes pulse2 {
		0% {
			opacity: 0.1;
			transform: scale(0);
		}

		50% {
			opacity: 0.4;
			transform: scale(2);
		}

		100% {
			opacity: 0;
			transform: scale(3);
		}
	}

	.camera-box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		text-align: center;
	}

	.camera-box u-icon {
		margin-bottom: 10px;
	}

	.camera-box view {
		font-size: 24rpx;
		color: #333;
	}



	//搜索框
	.input-container {
		width: 80%;
	}

	.input-box {
		display: flex;
		align-items: center;
		border: 1px solid #ccc;
		border-radius: 8rpx;
		padding: 10rpx 15rpx;
		background-color: #f9f9f9;
		width: 300px;
	}

	.input-field {
		flex: 1;
		height: 40rpx;
		font-size: 30rpx;
		border: none;
		outline: none;
		background-color: transparent;
	}

	.search-btn {
		padding: 0rpx 20rpx;
		/* 增大按钮范围 */
		background-color: #4CAF50;
		/* 添加底色 */
		color: white;
		border: none;
		/* 移除按钮的边框 */
		border-radius: 4rpx;
		/* 按钮圆角 */
		cursor: pointer;
		font-size: 14px;
		/* 设置字体大小 */
	}

	.input-icon {
		margin-left: 10rpx;
	}

	.container-bottom {
		position: fixed;
		bottom: 0px;
		margin-top: 10rpx;
		width: 100%;
	}

	.flex-row {
		display: flex;
		justify-content: space-around;
	}

	.flex-item {
		flex: 1;
		text-align: center;
		height: 75px;
	}

	.camera-box,
	.row-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	//vin搜索后
	.item {
		display: flex;
		flex-direction: row;
		margin: 10rpx 0;
		padding: 20rpx 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.label {
		color: #727272;
		width: 150rpx;
		/* 固定宽度，保持对齐 */
		text-align: justify;
		display: block;
		text-align-last: justify;
	}

	.value {
		margin-left: 30rpx;
		flex: 1;
	}

	.clickable {
		color: #007aff;
		cursor: pointer;
		text-decoration: underline;
	}

	.contact-name {
		font-size: 28rpx;
		/* 示例字体大小 */
		color: #333;
		/* 文字颜色 */
		display: inline-block;
		/* 保证下划线宽度和文字匹配 */
		border-bottom: 1px solid #a3a4aa;
		/* 自定义下划线颜色 */
		padding-bottom: 3rpx;
		/* 调整文字与下划线的间距 */
	}
</style>